<?php
class Frmcreator_IndexController extends Core_Controller_Action_Standard
{
    public function indexAction()
    {
        $url = $this->_getParam('url', '');
        $table = Engine_Api::_()->getDbTable('forms', 'frmcreator');
        $item = $table->getFormByUrl($url);        
        $viewer = Engine_Api::_()->user()->getViewer();
        if(!$item){
            return $this->_forward('requireauth', 'error', 'core');
        }
        
        $this->view->form = $form = new Frmcreator_Form_Form(array('form' => $item));
        
        //Validate Form
        if($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())){
            
            $values = $form->getValues();   
            $params = $recipients = array();
            $params['type'] = "frmcreator_contact_new";
            $recipients = explode(';', $item->email);
            
            //echo "<pre>". print_r($recipients, true). "</pre>";
            //die();
            
            $content = Engine_Api::_()->frmcreator()->renderEmailContent($values);
            //echo "<pre>". print_r($content, true). "</pre>";
            //die();
            
            // Main params
              $defaultParams = array(
                'host' => $_SERVER['HTTP_HOST'],                
                'date' => time(),
                'email' => $viewer->email,
                'sender_title' => $viewer->getTitle(),
                'sender_link' => $viewer->getHref(),
                'content' => $content                
              );
          
            $params['params'] = $defaultParams;
            try {
                $mailApi = Engine_Api::_()->getApi('mail', 'frmcreator');
                $mailApi->sendSystemRaw($recipients, $params['type'], $params['params']);
            } catch(Exception $ex){
                echo $ex->getMessage();
                die();   
            }
                     
            if(!empty($item->success_msg)){                
                $form->addNotice($item->success_msg);
            }
        }
    }
}
